package model

import (
	"fmt"
	"time"
)

// ==================== 请求模型 ====================

// StatisticsQueryReq 统计查询基础请求
type StatisticsQueryReq struct {
	Period    string `form:"period"`     // 快速查询: today/week/month/year
	StartDate string `form:"start_date"` // 自定义开始日期
	EndDate   string `form:"end_date"`   // 自定义结束日期
	GroupBy   string `form:"group_by"`   // 分组方式: day/week/month
}

// TrendsQueryReq 趋势查询请求
type TrendsQueryReq struct {
	Metric    string `form:"metric" binding:"required"`    // members/revenue/bookings
	Period    string `form:"period" binding:"required"`    // day/week/month/year
	StartDate string `form:"start_date" binding:"required"`
	EndDate   string `form:"end_date" binding:"required"`
}

// MemberDistributionReq 会员分布查询请求
type MemberDistributionReq struct {
	Dimension string `form:"dimension" binding:"required"` // type/status/gender/age
	StartDate string `form:"start_date"`
	EndDate   string `form:"end_date"`
}

// CourseRankingReq 课程排行查询请求
type CourseRankingReq struct {
	StartDate string `form:"start_date" binding:"required"`
	EndDate   string `form:"end_date" binding:"required"`
	OrderBy   string `form:"order_by"` // bookings/attendance/capacity_rate
	Limit     int    `form:"limit"`
}

// CoachWorkloadReq 教练工作量查询请求
type CoachWorkloadReq struct {
	CoachID   *uint  `form:"coach_id"`
	StartDate string `form:"start_date" binding:"required"`
	EndDate   string `form:"end_date" binding:"required"`
}

// RevenueQueryReq 营收查询请求
type RevenueQueryReq struct {
	Period    string `form:"period"`     // 快速查询: today/week/month/year
	StartDate string `form:"start_date"` // 自定义开始日期
	EndDate   string `form:"end_date"`   // 自定义结束日期
	GroupBy   string `form:"group_by"`   // day/week/month
	Type      string `form:"type"`       // all/recharge/card
}

// ==================== 响应模型 ====================

// OverviewResp 数据概览响应
type OverviewResp struct {
	Date    string             `json:"date"`
	Members MemberOverview     `json:"members"`
	Courses CourseOverview     `json:"courses"`
	Coaches CoachOverview      `json:"coaches"`
	Revenue RevenueOverview    `json:"revenue"`
	Cards   MembershipCardOverview `json:"cards"`
}

type MemberOverview struct {
	Total      int64   `json:"total"`
	NewToday   int64   `json:"new_today"`
	Active     int64   `json:"active"`
	Expired    int64   `json:"expired"`
	GrowthRate float64 `json:"growth_rate"`
}

type CourseOverview struct {
	Total          int64   `json:"total"`
	BookingsToday  int64   `json:"bookings_today"`
	CompletedToday int64   `json:"completed_today"`
	AttendanceRate float64 `json:"attendance_rate"`
}

type CoachOverview struct {
	Total        int64   `json:"total"`
	Active       int64   `json:"active"`
	AvgBookings  float64 `json:"avg_bookings"`
}

type RevenueOverview struct {
	Total      float64 `json:"total"`
	Today      float64 `json:"today"`
	ThisMonth  float64 `json:"this_month"`
	GrowthRate float64 `json:"growth_rate"`
}

type MembershipCardOverview struct {
	TotalActive  int64   `json:"total_active"`
	TotalBalance float64 `json:"total_balance"`
	ExpireSoon   int64   `json:"expire_soon"`
}

// TrendsResp 趋势响应
type TrendsResp struct {
	Metric     string          `json:"metric"`
	Period     string          `json:"period"`
	DataPoints []TrendDataPoint `json:"data_points"`
	Summary    TrendSummary    `json:"summary"`
}

type TrendDataPoint struct {
	Date       string  `json:"date"`
	Value      float64 `json:"value"`
	Cumulative float64 `json:"cumulative"`
}

type TrendSummary struct {
	Total float64 `json:"total"`
	Avg   float64 `json:"avg"`
	Max   float64 `json:"max"`
	Min   float64 `json:"min"`
}

// MemberGrowthResp 会员增长响应
type MemberGrowthResp struct {
	Period      string              `json:"period"`
	GroupBy     string              `json:"group_by"`
	TotalNew    int64               `json:"total_new"`
	DailyAvg    float64             `json:"daily_avg"`
	GrowthData  []MemberGrowthData  `json:"growth_data"`
}

type MemberGrowthData struct {
	Date        string `json:"date"`
	NewMembers  int64  `json:"new_members"`
	Cumulative  int64  `json:"cumulative"`
}

// MemberDistributionResp 会员分布响应
type MemberDistributionResp struct {
	Dimension    string                `json:"dimension"`
	Total        int64                 `json:"total"`
	Distribution []DistributionItem    `json:"distribution"`
}

type DistributionItem struct {
	Label      string  `json:"label"`
	Count      int64   `json:"count"`
	Percentage float64 `json:"percentage"`
}

// CourseRankingResp 课程排行响应
type CourseRankingResp struct {
	Period   string            `json:"period"`
	OrderBy  string            `json:"order_by"`
	Rankings []CourseRankItem  `json:"rankings"`
}

type CourseRankItem struct {
	Rank              int     `json:"rank"`
	CourseID          uint    `json:"course_id"`
	CourseName        string  `json:"course_name"`
	CoachName         string  `json:"coach_name"`
	TotalBookings     int64   `json:"total_bookings"`
	CompletedBookings int64   `json:"completed_bookings"`
	AttendanceRate    float64 `json:"attendance_rate"`
	AvgCapacityRate   float64 `json:"avg_capacity_rate"`
}

// CourseBookingTrendsResp 课程预约趋势响应
type CourseBookingTrendsResp struct {
	CourseID        uint                  `json:"course_id,omitempty"`
	CourseName      string                `json:"course_name,omitempty"`
	Period          string                `json:"period"`
	TotalBookings   int64                 `json:"total_bookings"`
	TotalCompleted  int64                 `json:"total_completed"`
	TotalCancelled  int64                 `json:"total_cancelled"`
	TotalNoShow     int64                 `json:"total_no_show"`
	BookingTrends   []BookingTrendData    `json:"booking_trends"`
}

type BookingTrendData struct {
	Date           string  `json:"date"`
	Bookings       int64   `json:"bookings"`
	Completed      int64   `json:"completed"`
	AttendanceRate float64 `json:"attendance_rate"`
}

// TimeslotStatsResp 时段分析响应
type TimeslotStatsResp struct {
	Period        string           `json:"period"`
	TimeslotStats []TimeslotData   `json:"timeslot_stats"`
	PeakHours     []int            `json:"peak_hours"`
}

type TimeslotData struct {
	Hour            int     `json:"hour"`
	Label           string  `json:"label"`
	Bookings        int64   `json:"bookings"`
	AvgCapacityRate float64 `json:"avg_capacity_rate"`
}

// CoachWorkloadResp 教练工作量响应
type CoachWorkloadResp struct {
	Period  string            `json:"period"`
	Coaches []CoachWorkload   `json:"coaches"`
	Summary CoachWorkloadSummary `json:"summary"`
}

type CoachWorkload struct {
	CoachID           uint     `json:"coach_id"`
	CoachName         string   `json:"coach_name"`
	Specialties       []string `json:"specialties"`
	TotalCourses      int64    `json:"total_courses"`
	TotalBookings     int64    `json:"total_bookings"`
	CompletedBookings int64    `json:"completed_bookings"`
	AttendanceRate    float64  `json:"attendance_rate"`
	TotalHours        float64  `json:"total_hours"`
	AvgRating         float64  `json:"avg_rating"`
	RatingCount       int64    `json:"rating_count"`
}

type CoachWorkloadSummary struct {
	TotalCoaches         int64   `json:"total_coaches"`
	AvgCoursesPerCoach   float64 `json:"avg_courses_per_coach"`
	AvgBookingsPerCoach  float64 `json:"avg_bookings_per_coach"`
	AvgRating            float64 `json:"avg_rating"`
}

// CoachRankingResp 教练排行响应
type CoachRankingResp struct {
	Period   string           `json:"period"`
	OrderBy  string           `json:"order_by"`
	Rankings []CoachRankItem  `json:"rankings"`
}

type CoachRankItem struct {
	Rank          int     `json:"rank"`
	CoachID       uint    `json:"coach_id"`
	CoachName     string  `json:"coach_name"`
	TotalBookings int64   `json:"total_bookings"`
	AvgRating     float64 `json:"avg_rating"`
	TotalHours    float64 `json:"total_hours"`
}

// RevenueOverviewResp 营收总览响应
type RevenueOverviewResp struct {
	Period          string                `json:"period"`
	TotalRevenue    float64               `json:"total_revenue"`
	RechargeRevenue float64               `json:"recharge_revenue"`
	CardRevenue     float64               `json:"card_revenue"`
	DailyAvg        float64               `json:"daily_avg"`
	GrowthRate      float64               `json:"growth_rate"`
	PaymentMethods  []PaymentMethodStats  `json:"payment_methods"`
}

type PaymentMethodStats struct {
	Method     string  `json:"method"`
	Amount     float64 `json:"amount"`
	Percentage float64 `json:"percentage"`
	Count      int64   `json:"count"`
}

// RevenueTrendsResp 营收趋势响应
type RevenueTrendsResp struct {
	Period  string            `json:"period"`
	GroupBy string            `json:"group_by"`
	Type    string            `json:"type"`
	Trends  []RevenueTrendData `json:"trends"`
	Summary RevenueSummary    `json:"summary"`
}

type RevenueTrendData struct {
	Date           string  `json:"date"`
	TotalRevenue   float64 `json:"total_revenue"`
	RechargeAmount float64 `json:"recharge_amount"`
	CardAmount     float64 `json:"card_amount"`
	OrderCount     int64   `json:"order_count"`
}

type RevenueSummary struct {
	Total float64 `json:"total"`
	Avg   float64 `json:"avg"`
	Max   float64 `json:"max"`
	Min   float64 `json:"min"`
}

// ConsumptionStatsResp 消费统计响应
type ConsumptionStatsResp struct {
	Period           string              `json:"period"`
	TotalConsumption float64             `json:"total_consumption"`
	TotalCount       int64               `json:"total_count"`
	AvgPerOrder      float64             `json:"avg_per_order"`
	ByType           []ConsumptionByType `json:"by_type"`
}

type ConsumptionByType struct {
	Type       string  `json:"type"`
	Amount     float64 `json:"amount"`
	Count      int64   `json:"count"`
	Percentage float64 `json:"percentage"`
}

// ==================== 内部统计结构 ====================

// DateRangeStats 日期范围统计基础结构
type DateRangeStats struct {
	StartDate time.Time
	EndDate   time.Time
}

// StatsCacheKey 统计缓存键结构
type StatsCacheKey struct {
	Type      string
	StartDate string
	EndDate   string
	ExtraKey  string
}

func (k StatsCacheKey) String() string {
	if k.ExtraKey != "" {
		return fmt.Sprintf("stats:%s:%s:%s:%s", k.Type, k.StartDate, k.EndDate, k.ExtraKey)
	}
	return fmt.Sprintf("stats:%s:%s:%s", k.Type, k.StartDate, k.EndDate)
}

// ==================== 统计常量 ====================

const (
	// 分组类型
	GroupByDay   = "day"
	GroupByWeek  = "week"
	GroupByMonth = "month"
	GroupByYear  = "year"

	// 指标类型
	MetricMembers  = "members"
	MetricRevenue  = "revenue"
	MetricBookings = "bookings"

	// 排序字段
	OrderByBookings      = "bookings"
	OrderByAttendance    = "attendance"
	OrderByCapacityRate  = "capacity_rate"
	OrderByRating        = "rating"
	OrderByWorkload      = "workload"

	// 统计维度
	DimensionType   = "type"
	DimensionStatus = "status"
	DimensionGender = "gender"
	DimensionAge    = "age"

	// 缓存时间
	CacheOverviewDuration = 5 * time.Minute  // 数据概览缓存5分钟
	CacheTrendsDuration   = 15 * time.Minute // 趋势数据缓存15分钟
	CacheStatsDuration    = 10 * time.Minute // 统计数据缓存10分钟
)
